import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Solution1 {
    public static void main(String[] args) {
        int[][] mat = new int[][]{{0, 0, 0}, {0, 1, 0}, {1, 1, 1}};
        int[][] res = updateMatrix(mat);
        for(int i = 0; i < res.length; i++) {
            for (int j = 0; j < res[0].length; j++)
                System.out.print(res[i][j] + " ");
            System.out.println();
        }

    }
    static int m;
    static int n;
    static int[] dx = {0, 0, 1, -1};
    static int[] dy = {1, -1, 0, 0};
    static Queue<int[]> q;
    static int[][] dist;
    public static int[][] updateMatrix(int[][] mat) {
        m = mat.length;
        n = mat[0].length;
        q = new LinkedList<>();
        dist = new int[m][n];
        // dist[i][j] == -1 : 标记当前位置没有被搜索过，存的是最短距离
        for(int i = 0; i < m; i++) {
            Arrays.fill(dist[i], -1);
        }

        // 1. 把所有的 0 加入队列 -- 把所有的源点加入队列
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(mat[i][j] == 0) {
                    q.add(new int[]{i, j});
                    dist[i][j] = 0;
                }
            }
        }

        // 2. 一层一层的往外扩
        while(!q.isEmpty()) {
            int[] t = q.poll();
            int a = t[0];
            int b = t[1];
            for(int k = 0; k < 4; k++) {
                int x = a + dx[k];
                int y = b + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && dist[x][y] == -1) {
                    q.add(new int[]{x, y});
                    dist[x][y] = dist[a][b] + 1;
                }
            }
        }
        return dist;
    }
}
